package com.draven.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.draven.mall.entity.MerchantApplication;
import com.draven.mall.mapper.MerchantApplicationMapper;
import com.draven.mall.service.MerchantAuditService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 商户审核服务实现类
 */
@Service
public class MerchantAuditServiceImpl implements MerchantAuditService {

    @Autowired
    private MerchantApplicationMapper merchantApplicationMapper;

    /**
     * 获取待审核的商户列表
     * @return 待审核的商户列表
     */
    @Override
    public List<MerchantApplication> getPendingMerchants() {
        return merchantApplicationMapper.selectPendingMerchants();
    }

    /**
     * 根据ID获取商户申请信息
     * @param id 商户ID
     * @return 商户申请信息
     */
    @Override
    public MerchantApplication getMerchantById(Long id) {
        return merchantApplicationMapper.selectById(id);
    }

    /**
     * 审核商户
     * @param id 商户ID
     * @param status 审核状态：1-通过，2-拒绝
     * @param rejectReason 拒绝原因（拒绝时必填）
     * @return 审核结果
     */
    @Override
    public boolean auditMerchant(Long id, Integer status, String rejectReason) {
        // 参数校验
        if (status != 1 && status != 2) {
            return false;
        }
        
        if (status == 2 && (rejectReason == null || rejectReason.trim().isEmpty())) {
            return false;
        }
        
        // 查找商户
        MerchantApplication application = getMerchantById(id);
        if (application == null) {
            return false;
        }
        
        // 更新审核状态
        Long auditorId = 1L; // 模拟当前管理员ID，实际应从认证信息获取
        int result = merchantApplicationMapper.updateMerchantStatus(id, status, rejectReason, auditorId);
        
        return result > 0;
    }

    /**
     * 获取商户列表
     * @param keyword 搜索关键词
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return 商户列表
     */
    @Override
    public Map<String, Object> getMerchantList(String keyword, Integer pageNum, Integer pageSize) {
        // 默认分页参数
        pageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;
        
        // 创建分页对象
        Page<MerchantApplication> page = new Page<>(pageNum, pageSize);
        
        // 执行分页查询
        IPage<MerchantApplication> pageResult = merchantApplicationMapper.selectMerchantsByKeyword(page, keyword);
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", pageResult.getRecords());
        result.put("total", pageResult.getTotal());
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        
        return result;
    }
} 